//
//  ClassViewController.m
//  FingerUniversity
//
//  Created by vantle on 16/3/12.
//  Copyright © 2016年 vantle. All rights reserved.
//

#import "ClassViewController.h"
#import "ClassCell.h"
#import "ClassDetailViewController.h"
#import "AFNetworking.h"
#import "SubClassViewController.h"
#import "SearchResultViewController.h"
#import "MTLJSONAdapter.h"
#import "File.h"
#import "MJRefresh.h"
#import "MobClick.h"
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
@interface ClassViewController ()

@end

@implementation ClassViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [MobClick beginLogPageView:@"ClassViewController"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ClassViewController"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    pageIndex=1;
    self.view.backgroundColor=[UIColor whiteColor];

    UIImageView*bg=[[UIImageView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    bg.image=[UIImage imageNamed:@"bg"];
    [self.view addSubview:bg];
    
    UIImageView*barImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, ScreenWidth, 44)];
    barImage.userInteractionEnabled=YES;
    barImage.backgroundColor=[UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
    [self.view addSubview:barImage];
    
    UIButton*backButton=[UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame=CGRectMake(0, 0, 100, 44);
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [barImage addSubview:backButton];
    
    UIImageView*backImage=[[UIImageView alloc]initWithFrame:CGRectMake(5, 12, 5, 20)];
    backImage.image=[UIImage imageNamed:@"back_arrowleft"];
    [barImage addSubview:backImage];
    
    _logoImage=[[UIImageView alloc]initWithFrame:CGRectMake(backImage.frame.origin.x+backImage.frame.size.width+3, 6, 32, 32)];
    _logoImage.layer.cornerRadius=3;
    _logoImage.clipsToBounds=YES;
    _logoImage.image=[UIImage imageNamed:@"app-logo-80"];
    [barImage addSubview:_logoImage];
    
    _noticeLabel=[[UILabel alloc]initWithFrame:CGRectMake(_logoImage.frame.origin.x+_logoImage.frame.size.width+5, 10, 100, 25)];
    _noticeLabel.text=@"我的课程";
    [barImage addSubview:_noticeLabel];
    
//    _searchButton=[UIButton buttonWithType:UIButtonTypeCustom];
//    _searchButton.center=CGPointMake(ScreenWidth-30, barImage.center.y-20);
//    _searchButton.bounds=CGRectMake(0, 0, 30, 35);
//    [_searchButton setBackgroundImage:[UIImage imageNamed:@"search32"] forState:UIControlStateNormal];
//    [_searchButton addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
//    [barImage addSubview:_searchButton];
//    
//    
//    _searchImage=[[UIImageView alloc]initWithFrame:CGRectMake(_logoImage.frame.origin.x+_logoImage.frame.size.width+10, _logoImage.frame.origin.y+26, 20, 20)];
//    _searchImage.image=[UIImage imageNamed:@"abc_ic_search_api_mtrl_alpha"];
//    _searchImage.hidden=YES;
//    [self.view addSubview:_searchImage];
//    
//    _searchLabel=[[UILabel alloc]initWithFrame:CGRectMake(_searchImage.frame.origin.x+_searchImage.frame.size.width+5, _searchImage.frame.origin.y, 100, 25)];
//    _searchLabel.text=@"搜索课程";
//    _searchLabel.hidden=YES;
//    _searchLabel.textColor=[UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:0.9];
//    _searchLabel.font=[UIFont systemFontOfSize:19];
//    [self.view addSubview:_searchLabel];
//    
//    _searchTextField =[[UITextField alloc]initWithFrame:CGRectMake(_logoImage.frame.origin.x+_logoImage.frame.size.width+10, _logoImage.frame.origin.y+20, ScreenWidth-_logoImage.frame.origin.x-_logoImage.frame.size.width-_searchButton.frame.size.width-20, 30)];
//    _searchTextField.enabled=NO;
//    _searchTextField.hidden=YES;
//    _searchTextField.delegate=self;
//    [self.view addSubview:_searchTextField];
//    
//    _lineView=[[UIImageView alloc]initWithFrame:CGRectMake(_searchTextField.frame.origin.x, _searchTextField.frame.origin.y+_searchTextField.frame.size.height, _searchTextField.frame.size.width+30, 1)];
//    _lineView.hidden=YES;
//    _lineView.backgroundColor=[UIColor blueColor];
//    [self.view addSubview:_lineView];
//    
//    _resultButtonImage=[[UIImageView alloc]init];
//    _resultButtonImage.center=CGPointMake(ScreenWidth-25,_searchImage.center.y );
//    _resultButtonImage.bounds=CGRectMake(0, 0, 10, 15);
//    _resultButtonImage.image=[UIImage imageNamed:@"abc_ic_go_search_api_mtrl_alpha"];
//    _resultButtonImage.hidden=YES;
//    [self.view addSubview:_resultButtonImage];
//    
//    _resuleButton=[UIButton buttonWithType:UIButtonTypeCustom];
//    _resuleButton.center=CGPointMake(ScreenWidth-25,_searchImage.center.y );
//    _resuleButton.bounds=CGRectMake(0, 0, 40, 44);
//    _resuleButton.hidden=YES;
//    [_resuleButton addTarget:self action:@selector(resultButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_resuleButton];
    
    _listArray=[[NSMutableArray alloc]initWithCapacity:0];
    
    
    [self setTableView];
    
    [self getClassInfo];
    
}
-(void)setTableView
{
    _tabelView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, _listArray.count*60)];
    _tabelView.dataSource=self;
    _tabelView.delegate=self;
    _tabelView.rowHeight=60;
    _tabelView.separatorColor=[UIColor whiteColor];
    _tabelView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_tabelView];
    [_tabelView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [_tabelView addFooterWithTarget:self action:@selector(footerRereshing)];
}
#pragma mark 开始进入刷新状态
-(void)headerRereshing
{
    pageIndex = 1;
    [self getClassInfo];
    [_tabelView headerEndRefreshing];
}
-(void)footerRereshing
{
    pageIndex += 1;
    [self getClassInfo];
    [_tabelView footerEndRefreshing];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString*cellIndentifier=@"cell";
    ClassCell*cell=[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell==nil) {
        cell=[[ClassCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    File*fileModel=_listArray[indexPath.row];
    int isDir=fileModel.isDir;
    if (isDir==1) {
        cell.myImage.image=[UIImage imageNamed:@"wenjian"];
    }
    else
    {
        cell.myImage.image=[UIImage imageNamed:@"图层-2"];
    }
    cell.titleLabel.text=[_listArray[indexPath.row] name];
    cell.backgroundColor=[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:0.5];
    cell.numberLabel.text=[NSString stringWithFormat:@"%d",(int)indexPath.row+1];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    File*fileModel=_listArray[indexPath.row];
    int isDir=fileModel.isDir;
    
    if (isDir==1) {
        SubClassViewController*subClassVC=[[SubClassViewController alloc]init];
        subClassVC.courseIdQu=fileModel.courseId;
        
        [self.navigationController pushViewController:subClassVC animated:YES];
    }
    else
    {
        ClassDetailViewController*classDetailVC=[[ClassDetailViewController alloc]init];
        classDetailVC.QuId=fileModel.courseId;
        [self.navigationController pushViewController:classDetailVC animated:YES];
    }
    
}
-(void)getClassInfo
{
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*userId=[userDefaults objectForKey:@"userId"];
    NSString*flag=[userDefaults objectForKey:@"flag"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes =[manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    
    NSDictionary*params=@{@"userId":userId,@"flag":flag,@"start":@"0",@"end":[NSString stringWithFormat:@"%d",pageIndex*12],@"name":@"",@"classify":@"0",@"speaker":@""};
//    manager.responseSerializer=[AFJSONResponseSerializer serializer];
    
    [manager POST:@"http://120.76.79.85:9080/mzdx/service/courseList.action" parameters:params success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData*responseData=responseObject;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        
        NSString*rType=[dic objectForKey:@"rType"];
        if ([rType isEqualToString:@"1"]) {
            [_listArray removeAllObjects];
            NSArray*coursesArray=[dic objectForKey:@"courses"];
            if ([coursesArray isKindOfClass:[NSArray class]]) {
                for (NSDictionary*tempDic in coursesArray) {
                    NSError *error = nil;
                    File*fileModel=[[File alloc]init];
                    fileModel=[MTLJSONAdapter modelOfClass:[File class] fromJSONDictionary:tempDic error:&error];
                    if (error==nil) {
                        [_listArray addObject:fileModel];
                        
                    }
                    
                }
                
            }
            
            [_tabelView reloadData];
            
            if ((ScreenHeight-64)/60>_listArray.count) {
                _tabelView.bounces=NO;
                _tabelView.frame=CGRectMake(0, 64, ScreenWidth, _listArray.count*60);
            }
            else
            {
                _tabelView.bounces=YES;
                _tabelView.frame=CGRectMake(0, 64, ScreenWidth, ScreenHeight-64);
            }
            
        }
        
    } failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

//-(void)searchButtonClick:(UIButton*)sender
//{
//    _noticeLabel.hidden=YES;
//    sender.hidden=YES;
//    _searchTextField.enabled=YES;
//    _searchTextField.hidden=NO;
//    _searchImage.hidden=NO;
//    _searchLabel.hidden=NO;
//    _lineView.hidden=NO;
//    _resuleButton.hidden=NO;
//    _resultButtonImage.hidden=NO;
//    
//}
//-(void)resultButtonClick
//{
//   
//    if (_searchTextField.text.length!=0) {
//        SearchResultViewController*searchResultVC=[[SearchResultViewController alloc]init];
//        self.searchText=_searchTextField.text;
//        searchResultVC.result=self.searchText;
//        [self.navigationController pushViewController:searchResultVC animated:YES];
//    }
//    
//}
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//    _searchImage.hidden=YES;
//    _searchLabel.hidden=YES;
//    return YES;
//}
//- (BOOL)textFieldShouldReturn:(UITextField *)textField
//{
//    [self.view endEditing:YES];
//    return YES;
//}
-(void)backButtonClick
{
//    if (_searchTextField.text.length!=0) {
//        _searchTextField.enabled=NO;
//        _searchTextField.text=nil;
//        _searchImage.hidden=YES;
//        _searchLabel.hidden=YES;
//        _searchButton.hidden=NO;
//        _lineView.hidden=YES;
//        _noticeLabel.hidden=NO;
//        _resuleButton.hidden=YES;
//        _resultButtonImage.hidden=YES;
//    }
//    else
//    {
//        [self.view endEditing:YES];
//        if (_searchImage.hidden==NO) {
//            _searchTextField.enabled=NO;
//            _searchImage.hidden=YES;
//            _searchLabel.hidden=YES;
//            _searchButton.hidden=NO;
//            _lineView.hidden=YES;
//            _noticeLabel.hidden=NO;
//            _resuleButton.hidden=YES;
//            _resultButtonImage.hidden=YES;
//        }
//        else
//        {
            [self.navigationController popViewControllerAnimated:YES];
//        }
//    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewDidLayoutSubviews
{
    if ([_tabelView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tabelView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([_tabelView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tabelView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


@end
